package com.hunk.core.excel;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import com.hunk.utils.io.Print;

/**Excel解析服务
 * @author Dengyx
 */
@Component
public class PoiService {
	/** 读取数据存入临时表
	 * 如有验证条件字段一定要在验证或处理字段之前
	 * @param path
	 * @param sheet
	 * @return
	 * 		  此次导入的临时表流水号
	 * @throws Exception
	 */
	public final String read(String path, PoiSheet sheet) 
			throws Exception {
		String _importUuid = sheet.getImport_uuid().toString();	//每次解析后，一批数据拥有一个uuid		
		InputStream _is = null;
		try {
			_is = new FileInputStream(path);
			try {
				HSSFWorkbook _hssfWorkbook = new HSSFWorkbook(_is);
		        HSSFSheet _hssfSheet = sheet.getParseSheet(_hssfWorkbook);		        
		        List<Map<String,String>> _paresedData = new ArrayList<Map<String,String>>(); 
		        // 从数据起始行dataBeginRow开始循环遍历
		        for (int rowNum = sheet.dataBeginRow; rowNum <= _hssfSheet.getLastRowNum(); rowNum++) {
		                HSSFRow _hssfRow = _hssfSheet.getRow(rowNum);
		                if (_hssfRow == null) {
		                    continue;
		                }
		                Map<String,String> _entityMap = sheet.parse(_hssfWorkbook,_hssfSheet,_hssfRow,_importUuid);
		                if (_entityMap != null)
		                	_paresedData.add(_entityMap);
		        }
		        // 解析完的数据将以key:value的形式保存到List<Map<String,String>>中
                Print.println(sheet.insertToTempTable(_paresedData));
			} catch (IOException e) {
				throw e;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw e;
		} finally {
			// 读取完毕必须将其io流关闭
			try {
				if (_is != null) {
					_is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return _importUuid;
	}
	
	/** 使用callback类完成对每一行的解析，更通用
	 * @param callback
	 * @return
	 * @throws VersionInCorrectException 
	 */
	public <T> List<T> read(PoiCallback<T> callback) throws VersionInCorrectException {
		String path = callback.getPath();
		List<T> list = new ArrayList<T>();
		
		InputStream is = null;
		try {
			is = new FileInputStream(path);
			try {
				HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
				callback.check(hssfWorkbook);
				// 循环工作表Sheet
				for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
		            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
		            if (hssfSheet == null) {
		                continue;
		            }
		            // 循环行Row
		            for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
		                HSSFRow hssfRow = hssfSheet.getRow(rowNum);
		                if (hssfRow == null) {
		                    continue;
		                }
		                // 调用自定义的解析回调函数		                
		                T o = callback.parse(hssfRow, hssfWorkbook, hssfSheet);
		                if (null != o) 
		                	list.add(o);
		            }
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			System.out.println("FileNotFound" + callback.getPath());
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return list;
	}
	
	
	@SuppressWarnings("unused")
	private static class Test {
	/** 测试方法
	 * @param args
	 * @throws Throwable
	 */
	public static void main(String[] args) throws Throwable {
		ApplicationContext context = 
				new ClassPathXmlApplicationContext("/META-INF/poi_excel.xml");
		// an ApplicationContext is also a BeanFactory (via inheritance)
		BeanFactory factory = context;
		PoiSheet poiSheet_fxdx = (PoiSheet)factory.getBean("poiSheet_fxdx");
		
		Print.println(poiSheet_fxdx.excelTemplateName);	
		Print.println(poiSheet_fxdx.poiFields);
		
		PoiService poiService = (PoiService) factory.getBean("poiService");
//		Import_Id import_id = (Import_Id) factory.getBean("import_Id");
//		Print.println(import_id.reimplement(null, null, null).toString());
		poiService.read("C:/Documents and Settings/admin/桌面/奉贤区导入表模版_4.xls", poiSheet_fxdx);
	}
	}
}
